/**
 * 废弃2021/3/5 权限修改,改为套件FunctionManagemen  --hzq
 */

import React, { useState, useEffect } from 'react';
import { Form, Table, message, Input, Popover, Badge } from 'antd';
import { withRouter } from 'umi';
import TreeSelectPro from '@/components/TreeSelectPro/TreeSelectPro';
import { getQueryBusinessData } from '@/pages/WorkFlow/services';
import Difference from '@/pages/WorkFlow/components/FormControls/components/Difference';
import AutoRenderComponent from '@/pages/WorkFlow/components/FormControls/components/AutoRenderComponent/AutoRenderComponent';
import { fetchDutyListByOrganization } from './services';
import styles from './index.less';

const gradeType = {
    1: '基础',
    2: '职能',
    3: '高级'
};

// const statusType = {
//     0: '启用',
//     1: '禁用'
// };

export const AUTH = {
    1: '菜单',
    2: '页面',
    3: '按钮'
};

// 权限管理流程
const AuthManage = ({ dataSource, form, location, formValueMap = {}, wrapperLayout }) => {
    const { children: list = [] } = dataSource;
    const hiDataId = location?.query?.hiDataId || formValueMap?.hiDataId;
    const [approveDataLoading, setApproveDataLoading] = useState(false);
    const [approveData, setApproveData] = useState(null);
    const [highestGradeType, setHighestGradeType] = useState(null);
    const { getFieldDecorator } = form;
    const [treeDataLoading, setTreeDataLoading] = React.useState(false);
    const [treeData, setTreeData] = React.useState([]);
    const [treeSelectDataSource, setTreeSelectDataSource] = React.useState([]);

    const compareChanged = (record, field, objEnum) => {
        const { oldBusinessData = {}, compareDataField } = record;
        const { updateFieldNames = [] } = compareDataField;
        const objKeys = Object.keys(oldBusinessData);
        const compareFound = updateFieldNames.includes(field);
        const oldFound = objKeys.includes(field);
        if (compareFound) {
            if (oldFound) {
                return objEnum ? objEnum[oldBusinessData[field]] : oldBusinessData[field];
            }
            return '';
        }
        return undefined;
    };

    // 获取授权列表
    useEffect(() => {
        const fetchDutyCodes = async () => {
            setTreeDataLoading(true);
            const result = await fetchDutyListByOrganization({ showTreeFlag: 1 });
            const { code, data, msg } = result;
            if (code === 10000) {
                setTreeData(data);
            } else {
                message.error(msg);
            }
            setTreeDataLoading(false);
        };
        fetchDutyCodes();
    }, []);

    useEffect(() => {
        const filterDuties = tree =>
            tree.map(i => ({
                title: i.dutyAlias,
                value: i.dutyCode,
                key: i.dutyCode
            }));

        const filterTree = tree =>
            tree.map(({ children, organizationName, organizationCode, duties, ...props }) => {
                if ((children && children.length > 0) || (duties && duties.length > 0)) {
                    return {
                        children: [...filterTree(children), ...filterDuties(duties)],
                        title: organizationName,
                        value: organizationCode,
                        key: organizationCode,
                        disableCheckbox: false,
                        ...props
                    };
                }
                return {
                    children: '',
                    title: organizationName,
                    value: organizationCode,
                    key: organizationCode,
                    disableCheckbox: !!(!children?.length && !duties?.length),
                    ...props
                };
            });
        const result = filterTree(treeData);
        setTreeSelectDataSource(result);
    }, [treeData]);

    const columns = [
        {
            title: '功能',
            dataIndex: 'name',
            key: 'name',
            width: 200,
            render: text => <span>{text}</span>
        },
        {
            title: '类型',
            width: 100,
            dataIndex: 'type',
            render: text => AUTH[text] || ''
        },
        // {
        //     title: '简介',
        //     dataIndex: 'description',
        //     key: 'description',
        //     render: (text, record) => (
        //         <Difference tip={compareChanged(record, 'description')} className={styles.tableDeff}>
        //             <span>{text}</span>
        //         </Difference>
        //     )
        // },
        {
            title: '等级',
            width: 160,
            dataIndex: 'gradeType',
            key: 'gradeType',
            render: (text, record) => (
                <Difference tip={compareChanged(record, 'gradeType', gradeType)} className={styles.tableDeff}>
                    <span>{gradeType[text]}</span>
                </Difference>
            )
        },
        {
            title: '授权',
            dataIndex: 'dutyCodes',
            render: (text, record, index) => {
                const { compareDataField, dutyCodes = [] } = record;
                const { add_resource: addResource = [], delete_resource: deleteResource = [] } =
                    compareDataField.seniorUpdateContent || {};
                const compareFound = addResource.length || deleteResource.length;
                return (
                    <div className={`${styles.treeSelectBox} ${compareFound ? styles.differenceBox : null}`}>
                        {compareFound ? (
                            <Popover
                                content={
                                    <div className={styles.authModifyWrap}>
                                        {addResource.map(item => (
                                            <div className={styles.modifyContent}>
                                                <Badge status="success" style={{ width: '14px' }} />
                                                <p>新增：{item}</p>
                                            </div>
                                        ))}
                                        {deleteResource.map(item => (
                                            <div className={styles.modifyContent}>
                                                <Badge status="error" style={{ width: '14px' }} />
                                                <p>删除：{item}</p>
                                            </div>
                                        ))}
                                    </div>
                                }
                                title="变更内容"
                                placement="leftTop"
                                arrowPointAtCenter
                                overlayClassName={styles.postAuthPopover}
                                getPopupContainer={node => node}
                            >
                                <div>
                                    <Form.Item style={{ margin: 0 }}>
                                        {getFieldDecorator(`dutyCodes[${index}]`, {
                                            initialValue: dutyCodes
                                        })(
                                            <TreeSelectPro
                                                loading={treeDataLoading}
                                                treeData={treeSelectDataSource}
                                                dropdownClassName={styles.disabledTreeSelect}
                                                getPopupContainer={node => node}
                                                treeCheckable
                                                showSearch={false}
                                                treeDefaultExpandedKeys={
                                                    treeSelectDataSource.length > 0
                                                        ? [treeSelectDataSource[0]?.key || '']
                                                        : []
                                                }
                                                style={{ width: '100%' }}
                                                dropdownStyle={{ maxHeight: 300 }}
                                                placeholder="请选择授权"
                                                maxTagCount={5}
                                            />
                                        )}
                                    </Form.Item>
                                </div>
                            </Popover>
                        ) : (
                            <Form.Item style={{ margin: 0 }}>
                                {getFieldDecorator(`dutyCodes[${index}]`, {
                                    initialValue: dutyCodes
                                })(
                                    <TreeSelectPro
                                        loading={treeDataLoading}
                                        treeData={treeSelectDataSource}
                                        dropdownClassName={styles.disabledTreeSelect}
                                        getPopupContainer={node => node}
                                        treeCheckable
                                        treeDefaultExpandedKeys={
                                            treeSelectDataSource.length > 0 ? [treeSelectDataSource[0]?.key || ''] : []
                                        }
                                        style={{ width: '100%' }}
                                        dropdownStyle={{ maxHeight: 300 }}
                                        placeholder="请选择授权"
                                        maxTagCount={5}
                                    />
                                )}
                            </Form.Item>
                        )}
                    </div>
                );
            }
        }
        // {
        //     title: '状态',
        //     dataIndex: 'status',
        //     key: 'status',
        //     render: text => <span className={text === 1 ? styles.disabled : null}>{statusType[text]}</span>
        // }
    ];

    // 拉取审批数据
    useEffect(() => {
        const fetchApproveData = async () => {
            setApproveDataLoading(true);
            const { msg, code, data = [] } = await getQueryBusinessData(hiDataId);
            if (code === 10000) {
                setApproveData([...data]);
                if (data.length > 0) {
                    const hgt = data.sort((a, b) => a.gradeType - b.gradeType)[data.length - 1];
                    setHighestGradeType(hgt?.gradeType || 1);
                }
            } else {
                message.error(msg);
            }
            setApproveDataLoading(false);
        };
        if (hiDataId) {
            fetchApproveData();
        }
    }, [hiDataId]);

    return (
        <div className={styles.authManageWrapper}>
            <div className={styles.formIntro}>
                <span>权限申请流程</span>
                <div className={styles.info}>以下是权限申请详情，请审阅</div>
            </div>
            <Form {...wrapperLayout}>
                {list.map(item => {
                    const { label, formId, rules, extra } = item;
                    let { initialValue } = item;

                    if (formId === 'dutyAuth') {
                        initialValue = highestGradeType;
                    }

                    if (formId === 'dutyAuthName') {
                        initialValue = gradeType[highestGradeType];
                    }

                    return (
                        <Form.Item
                            label={label}
                            key={formId}
                            extra={extra}
                            style={{ display: item?.inRenderDom === false ? 'none' : 'block' }}
                        >
                            {getFieldDecorator(formId, {
                                initialValue,
                                rules
                            })(<AutoRenderComponent form={form} config={item} />)}
                        </Form.Item>
                    );
                })}
                <Form.Item style={{ display: 'none' }}>
                    {getFieldDecorator('hiDataId', {
                        initialValue: hiDataId
                    })(<Input />)}
                </Form.Item>
                <Form.Item label="功能权限">
                    <Table
                        rowKey="code"
                        loading={approveDataLoading}
                        columns={columns}
                        dataSource={approveData}
                        pagination={false}
                    />
                </Form.Item>
            </Form>
        </div>
    );
};

export default withRouter(AuthManage);
